package com.spark.lola.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spark.lola.mapper.StoreInfoMapper;
import com.spark.lola.service.IStoreInfoService;
import com.spark.lola.support.common.util.TimeUtil;
import com.spark.lola.support.core.entity.KafkaMessage;
import com.spark.lola.support.warehouse.configuration.WarehouseKafkaTopic;
import com.spark.lola.support.warehouse.constant.WarehouseCache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.spark.lola.support.mybatis.controller.BaseController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spark.lola.entity.warehouse.StoreInfo;
import com.spark.lola.support.common.constant.CommonConstant;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.DataBeanUtils;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.mybatis.entity.PageParam;
import com.spark.lola.support.mybatis.entity.QueryParam;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 仓库 前端控制器
 * </p>
 *
 * @author dengyejun
 * @since 2020-06-10
 */
@RestController
@RequestMapping("/api/store-info")
public class StoreInfoController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(StoreInfoController.class);
    @Autowired
    private StoreInfoMapper currentMapper;
    @Autowired
    private IStoreInfoService currentService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @RequestMapping(value = "map")
    public ResponseBean map(@RequestParam("key")String key) {
        return ResponseBean.success(currentService.selectMap(key));
    }

    @RequestMapping("/existNo")
    public ResponseBean existNo(@RequestParam String no,@RequestParam(value = "id",defaultValue = "0") Long id) {
        if(id>0){
            return ResponseBean.success(null,0);
        }
        Long storeId = Long.valueOf(no);
        if(currentMapper.selectById(storeId)!=null){
            return ResponseBean.success(null,1);
        }
        return ResponseBean.success(null,0);
    }


    @RequiresPermissions(value = "m7110")
    @RequestMapping(value = "/findBy", consumes = "application/json")
    public ResponseBean findBy(@RequestBody QueryParam<StoreInfo> queryBean,
                               @SessionAttribute ShiroUser shiroUser) {
        PageParam<StoreInfo> pageParam = queryBean.toPageParam();
        IPage<StoreInfo> page = currentService.page(pageParam.getPage(), pageParam.getEntityWrapper());
        return ResponseBean.success(page);
    }

    @RequiresPermissions(value = "m7114")
    @RequestMapping(value = "/findInfo/{id}", method = RequestMethod.GET)
    public ResponseBean findInfo(@PathVariable Long id,
                                 @SessionAttribute ShiroUser shiroUser) {
        StoreInfo model;
        if (id == 0) {
            model = new StoreInfo();
        } else {
            model = currentService.getById(id);
        }
        return ResponseBean.success(model);
    }

    @RequiresPermissions(value = {"m7111", "m7113"}, logical = Logical.OR)
    @RequestMapping(value = "/save", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean save(@RequestBody StoreInfo form, @SessionAttribute ShiroUser shiroUser) throws Exception {
        StoreInfo model = new StoreInfo();
        if (form.getId() != null) {
            // 禁止修改项 做空处理
            model = currentService.getById(form.getId());
        }else{
            model.setId(Long.valueOf(form.getNo()));
        }
        DataBeanUtils.buildUpdateBean(model, form);
        currentService.saveOrUpdate(model);
        if(!StringUtils.isEmpty(model.getRemark())) {
            WarehouseCache.organSecretKeys.put(model.getNo(), model.getRemark());
        }
        return ResponseBean.success(model);
    }

    @RequiresPermissions(value = "m7115")
    @RequestMapping("/on")
    public ResponseBean on(@RequestParam String nos) {
        int count = currentService.updateUsedByIds(CommonConstant.Y, nos);
        return ResponseBean.success(null, count);
    }

    @RequiresPermissions(value = "m7116")
    @RequestMapping("/un")
    public ResponseBean un(@RequestParam String nos) {
        int count = currentService.updateUsedByIds(CommonConstant.N, nos);
        return ResponseBean.success(null, count);
    }

    @RequiresPermissions(value = "m7112")
    @RequestMapping("/del")
    public ResponseBean del(@RequestParam(value = "nos") List<Long> ids) {
        ids.forEach(id -> {
            currentService.removeById(id);
        });
        return ResponseBean.success();
    }

    @RequiresPermissions(value = "m7117")
    @RequestMapping(value = "/init/{id}", method = RequestMethod.GET)
    @Transactional
    public ResponseBean init(@PathVariable Long id,
                                 @SessionAttribute ShiroUser shiroUser) {
        StoreInfo model = currentService.getById(id);
        kafkaTemplate.send(WarehouseKafkaTopic.INIT_SOTRE,model.getId().toString(), JSON.toJSONString(model));
        return ResponseBean.success();
    }


    @RequestMapping(value = "/syncOrder/{id}", method = RequestMethod.GET)
    @Transactional
    public ResponseBean syncOrder(@PathVariable Long id,
                                  @RequestParam(value = "start",defaultValue = "")String start,
                                  @RequestParam(value = "end",defaultValue = "")String end,
                             @SessionAttribute ShiroUser shiroUser) {
        StoreInfo model = currentService.getById(id);
        if(StringUtils.isEmpty(start)){
            start = TimeUtil.getCurrentDate();
        }
        if(StringUtils.isEmpty(end)){
            end = TimeUtil.getCurrentDate();
        }
        JSONObject request = new JSONObject();
        request.put("start", start);
        request.put("end", end);
        kafkaTemplate.send(WarehouseKafkaTopic.SYNC_STORE_ORDER, model.getId().toString(), request.toJSONString());
        return ResponseBean.success();
    }
}
